import { useEffect } from "react";
import { Tooltip, Table } from "antd";
import { Card as SemiCard, ButtonGroup, Button } from "@douyinfe/semi-ui";
import { IconRefresh } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import dayjs from "dayjs";
import { format } from "timeago.js";

import { OnlinePersons } from "../../_graphql/platforms";

const { Column } = Table;

const PlatformServers = () => {
    const { windowInnerHeight, graphqlFetchPlatform } = useModel("global");

    const state = useReactive({
        loading: false,
        onlinePersons: [],
    });

    const loadOnlinePersons = async () => {
        state.loading = true;
        let res = await graphqlFetchPlatform({ query: OnlinePersons, variables: {} });
        state.onlinePersons = res?.a?.nodes || [];
        state.loading = false;
    };

    useEffect(() => {
        loadOnlinePersons();
    }, []);

    // 窗口头部：30，应用头：60，操作区内边距：24，卡面头：53，修正值：4
    const cardBodyHeight = windowInnerHeight - 90 - 20 - 53 - 4;

    return (
        <div style={{ padding: 10 }}>
            <SemiCard
                title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>在线用户信息</span>}
                headerExtraContent={
                    <ButtonGroup>
                        <Button icon={<IconRefresh />} onClick={loadOnlinePersons}>
                            重新加载
                        </Button>
                    </ButtonGroup>
                }
                headerStyle={{ padding: "10px 14px" }}
                shadows="always"
                bordered={false}
                bodyStyle={{ padding: 0, height: cardBodyHeight }}
            >
                <Table loading={state.loading} dataSource={state.onlinePersons} size="small" pagination={false} rowKey="peerId" scroll={{ y: cardBodyHeight - 46 }}>
                    <Column title="用户姓名" dataIndex="person.realName" align="center" render={(_, r) => r.person?.realName || "-"} />
                    <Column title="UUID" dataIndex="personUuid" align="center" />
                    <Column title="节点ID" dataIndex="peerId" align="center" width={500} />
                    <Column
                        title="上线时间"
                        dataIndex="onlineTime"
                        align="center"
                        render={(_) => _ && <Tooltip title={dayjs(Number(_)).format("YYYY年MM月DD日 HH:ss:mm")}>{format(_, "zh_CN")}</Tooltip>}
                    />
                </Table>
            </SemiCard>
        </div>
    );
};

export default PlatformServers;
